//
//  LoopViewController.swift
//  Loop
//
//  Created by thomas on 2020/9/23.
//

import UIKit

class LoopViewController: UIViewController {

    @IBOutlet var tableView: UITableView!
    @IBOutlet var errorView: UIView!
    @IBOutlet var errorLabel: UILabel!

    private var timer: Timer!
    private var dict: [String: String]?

    // MARK: - LifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()

        initialize()
        configUI()
        laodLastResultFromDB()
    }

    // MARK: - UI
    private func initialize() {
        timer = Timer(timeInterval: 5, repeats: true, block: { [weak self] t in
            self?.fetchData()
        })
        RunLoop.current.add(timer, forMode: .common)
    }

    private func configUI() {
        tableView.tableFooterView = UIView()
    }

    private func showErrorView(msg: String) {

        errorView.isHidden = false
        tableView.isHidden = true
        errorLabel.text = msg
    }

    private func showDataView(_ dict: [String: String]?) {

        self.dict = dict
        errorView.isHidden = true
        tableView.isHidden = false
        tableView.reloadData()
    }

    // MARK: - Data
    private func laodLastResultFromDB() {

        guard let result = StoreService.shared.getLastRequestResult() else {
            return
        }

        if let errorMsg = result.errorMsg {
            self.showErrorView(msg: errorMsg)
            return
        }

        guard let data = result.data,
              let dict: [String: String] = Parser.parse(json: data) else {
            self.showErrorView(msg: "解析Json数据错误")
            return
        }

        self.showDataView(dict)
    }

    private func fetchData() {

        view.makeToastActivity(.center)

        APIService.shared.fetchData(method: .get) { [weak self] (dict: Dictionary<String, String>?, error) in

            self?.view.hideToastActivity()

            if let error = error {
                self?.showErrorView(msg: error.localizedDescription)
                return
            }

            self?.showDataView(dict)
        }
    }
}

// MARK: - UITableViewDataSource
extension LoopViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dict?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")
        if cell == nil {
            cell = UITableViewCell(style: .value2, reuseIdentifier: "UITableViewCell")
            cell!.selectionStyle = .none
        }

        guard let dict = dict else {
            return cell!
        }

        let key = [String](dict.keys)[indexPath.row]
        let value = dict[key]

        cell?.textLabel?.text = key
        cell?.detailTextLabel?.text = value

        return cell!
    }
}
